<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>层级模型节点命名、查找、遍历</title>
    <script src="http://www.yanhuangxueyuan.com/versions/threejsR92/build/three.js"></script>
    <link rel="stylesheet" href="common.css">
</head>

<body>

</body>
<script>
    // 创建场景
    let scene = new THREE.Scene();

    // 创建面板
    let planeGeometry = new THREE.PlaneGeometry(150, 70); // 平面网格
    let planeMaterial = new THREE.MeshLambertMaterial({
        color: 0xffffff
    });
    let plane = new THREE.Mesh(planeGeometry, planeMaterial);
    plane.rotateX(-Math.PI / 2);
    plane.receiveShadow = true; // 设置接收阴影的投影面
    scene.add(plane);

    // 创建模型
    var faceMesh = sphereMesh(10, 0, 0, 0)
    faceMesh.name = '脸'
    var eye1Mesh = sphereMesh(4, 7, 6, 0)
    eye1Mesh.name = '左眼'
    var eye2Mesh = sphereMesh(4, 0, 6, 7)
    eye2Mesh.name = '右眼'

    // 打组
    var headGroup = new THREE.Group()
    headGroup.name = '头部结构'
    headGroup.add(faceMesh, eye1Mesh, eye2Mesh)
    headGroup.position.y = 25
    headGroup.children.forEach(item => {
        item.castShadow = true //遍历组，设置mesh阴影
        if (item.name == '左眼' || item.name == '右眼') {
            item.material.color.set(0x00ff00)
        }
    })
    scene.add(headGroup);

    // 【第三步：设置光源-聚光灯】
    let spotLight = new THREE.SpotLight(0xffffff);
    spotLight.angle = Math.PI / 6 // 设置聚光光源发散角度
    spotLight.position.set(-20, 100, 40);
    spotLight.shadowDarkness = 0.3;
    spotLight.target = headGroup
    spotLight.castShadow = true; // 设置灯光生成阴影
    scene.add(spotLight);


    // 【第三步：相机设置】
    var width = window.innerWidth; //窗口宽度
    var height = window.innerHeight; //窗口高度
    var k = width / height; //窗口宽高比
    var s = 70; //三维场景显示范围控制系数，系数越大，显示的范围越大
    var camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000); //创建相机对象
    camera.position.set(200, 300, 200); //设置相机位置
    camera.lookAt(scene.position); //设置相机方向(指向的场景对象)

    //设置辅助线
    var axisHelper = new THREE.AxisHelper(600); // 辅助坐标系
    // scene.add(axisHelper);
    var spotLightHelper = new THREE.SpotLightHelper(spotLight, "#ffffff"); //聚光源辅助对象
    scene.add(spotLightHelper);


    // 【第四步：渲染对象】
    var renderer = new THREE.WebGLRenderer();
    renderer.setSize(width, height); //设置渲染区域尺寸
    renderer.setClearColor(0xb9d3ff, 0.3); //设置背景颜色
    renderer.shadowMap.enabled = true; //渲染阴影
    document.body.appendChild(renderer.domElement); //body元素中插入canvas对象
    renderer.render(scene, camera); //执行渲染操作（场景、相机）



    // 封装创建模型,球体网格模型创建函数
    function sphereMesh(R, x, y, z) {
        var geometry = new THREE.SphereGeometry(R, 25, 25);
        var material = new THREE.MeshPhongMaterial({
            color: 0x0000ff
        });
        var mesh = new THREE.Mesh(geometry, material);
        mesh.position.set(x, y, z);
        return mesh;
    }
</script>

</html>